<template>
  <div class="page-container">
    <BridgeVerticalTabNav :bridge-id="bridgeIdFromRoute" />
    
    <div class="bridge-health-container">
      <!-- 顶部操作栏 -->
      <div class="operation-bar">
        <div class="left">
          <span>桥梁健康数据</span>
          <!-- <el-select
            v-model="currentPageValue"
            class="page-selector"
            @change="handlePageChange"
          >
            <el-option
              v-for="item in pageOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :class="{ 'is-active': item.value === currentPageValue }"
            />
          </el-select> -->
        </div>
        <div class="right">
          <el-button type="primary" @click="handleAdd" class="custom-button">
            <i class="el-icon-plus"></i> 新增数据
          </el-button>
          <!-- <el-button type="danger" @click="handleBatchDelete" class="custom-button">
            <i class="el-icon-delete"></i> 批量删除
          </el-button> -->
        </div>
      </div>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        class="custom-table"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="bridgeName" label="桥梁名称" min-width="120">
          <template #default="{ row }">
            <span class="bridge-name">
              {{
                bridgeOptions.find((item) => item.value === row.bridgeId)?.label ||
                row.bridgeName
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="inspectionTime" label="检测时间" width="160" />
        <el-table-column prop="inspectionUnit" label="检测单位" width="160" />
        <el-table-column prop="inspectionMethod" label="检测方法" width="160" />
        <el-table-column prop="healthScore" label="健康评分" width="100">
          <template #default="{ row }">
            <el-tag :type="getHealthScoreType(row.healthScore)">
              {{ row.healthScore }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="mainIssues"
          label="发现的问题"
          min-width="120"
          align="center"
        >
          <template #default="scope">
            <span class="ellipsis-text" @click="showIssues(scope.row)">
              {{ (scope.row.mainIssues || "暂无问题记录").slice(0, 20) }}
              {{ scope.row.mainIssues?.length > 20 ? "..." : "" }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="measure" label="维护措施" min-width="120" align="center">
          <template #default="scope">
            <span class="ellipsis-text" @click="showMeasures(scope.row)">
              {{ (scope.row.measure || "暂无维护措施").slice(0, 20) }}
              {{ scope.row.measure?.length > 20 ? "..." : "" }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="reportFilePath" label="报告文件" width="120" align="center">
          <template #default="scope">
            <el-button link type="primary" @click="showReport(scope.row)">
              查看文件
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remarks" min-width="120" align="center">
          <template #default="scope">
            <span class="ellipsis-text" @click="showRemarks(scope.row)">
              {{ (scope.row.remarks || "暂无备注").slice(0, 20) }}
              {{ scope.row.remarks?.length > 20 ? "..." : "" }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleView(row)" class="operation-button">
              详情
            </el-button>
            <el-button link @click="handleDelete(row)" class="operation-button danger">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          background
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 新增/编辑弹窗 -->
      <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="50%"
        class="custom-dialog"
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120px"
          class="dialog-form"
        >
          <el-form-item label="选择桥梁" prop="bridgeId">
            <el-select v-model="form.bridgeId" placeholder="请选择桥梁" style="width: 100%">
              <el-option
                v-for="item in bridgeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="检测时间" prop="inspectionTime">
            <el-date-picker
              v-model="form.inspectionTime"
              type="datetime"
              placeholder="选择检测时间"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="检测单位" prop="inspectionUnit">
            <el-input v-model="form.inspectionUnit" placeholder="请输入检测单位" />
          </el-form-item>
          <el-form-item label="检测方法" prop="inspectionMethod">
            <el-input v-model="form.inspectionMethod" placeholder="请输入检测方法" />
          </el-form-item>
          <el-form-item label="健康状况评分" prop="healthScore">
            <el-input-number
              v-model="form.healthScore"
              :min="0"
              :max="100"
              :precision="1"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="发现的问题" prop="mainIssues">
            <el-input
              type="textarea"
              v-model="form.mainIssues"
              :rows="3"
              placeholder="请输入发现的问题"
            />
          </el-form-item>
          <el-form-item label="维护措施" prop="measure">
            <el-input
              type="textarea"
              v-model="form.measure"
              :rows="3"
              placeholder="请输入维护措施"
            />
          </el-form-item>
          <el-form-item label="报告文件" prop="reportFilePath">
            <el-input v-model="form.reportFilePath" placeholder="请输入报告文件路径" />
          </el-form-item>
          <el-form-item label="备注信息" prop="remarks">
            <el-input
              type="textarea"
              v-model="form.remarks"
              :rows="3"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </template>
      </el-dialog>

      <!-- 备注信息弹窗 -->
      <el-dialog v-model="remarksDialogVisible" title="备注信息" width="40%">
        <div style="white-space: pre-wrap">{{ currentRemarks }}</div>
        <template #footer>
          <span>
            <el-button @click="remarksDialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 添加新的弹窗 -->
      <el-dialog v-model="issuesDialogVisible" title="发现的问题" width="40%">
        <div style="white-space: pre-wrap">{{ currentIssues }}</div>
        <template #footer>
          <span>
            <el-button @click="issuesDialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>

      <el-dialog v-model="measuresDialogVisible" title="维护措施" width="40%">
        <div style="white-space: pre-wrap">{{ currentMeasures }}</div>
        <template #footer>
          <span>
            <el-button @click="measuresDialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>

      <el-dialog v-model="reportDialogVisible" title="报告文件路径" width="40%">
        <div style="white-space: pre-wrap">{{ currentReport }}</div>
        <template #footer>
          <span>
            <el-button @click="reportDialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getBridgeHealthReportList,
  getBridgeHealthReportById,
  addBridgeHealthReport,
  updateBridgeHealthReport,
  deleteBridgeHealthReport,
} from "@/api/bridge/bisc/bridge";
import { getBridgeList } from "@/api/bridge/bisc/bridge";
import dayjs from "dayjs";
import { useRouter, useRoute } from "vue-router";
import BridgeVerticalTabNav from '../components/BridgeVerticalTabNav.vue';

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const searchQuery = ref("");
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedRows = ref([]);

// 获取路由参数
const router = useRouter();
const route = useRoute();
const bridgeIdFromRoute = ref<string | null>(null);

// 页面选择相关
const currentPageValue = ref('health');
const pageOptions = ref([
  { label: '桥梁健康数据', value: 'health' },
  { label: '桥梁保养周期', value: 'cycle' },
  { label: '维护保养记录', value: 'maintenance' }
]);

// 页面跳转处理
const handlePageChange = (value: string) => {
  // 保持当前的bridgeId参数
  const query = bridgeIdFromRoute.value ? { bridgeId: bridgeIdFromRoute.value } : {};
  
  if (value === 'cycle') {
    router.push({ path: '/basic-data/three-pages/bridge', query });
  } else if (value === 'maintenance') {
    router.push({ path: '/basic-data/four-pages/bridge', query });
  } else if (value === 'health') {
    router.push({ path: '/basic-data/two-pages/bridge', query });
  }
};

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref("");
const formRef = ref();
const form = ref({
  id: "",
  bridgeId: "",
  bridgeName: "",
  inspectionTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
  inspectionUnit: "",
  inspectionMethod: "",
  healthScore: 0,
  mainIssues: "",
  measure: "",
  reportFilePath: "",
  remarks: "",
});

// 备注弹窗相关
const remarksDialogVisible = ref(false);
const currentRemarks = ref("");

// 新添加的弹窗相关
const issuesDialogVisible = ref(false);
const measuresDialogVisible = ref(false);
const reportDialogVisible = ref(false);
const currentIssues = ref("");
const currentMeasures = ref("");
const currentReport = ref("");

// 添加桥梁列表相关的响应式变量
const bridgeOptions = ref([]);

// 表单校验规则
const rules = {
  bridgeId: [{ required: true, message: "请选择桥梁", trigger: "change" }],
  inspectionTime: [{ required: true, message: "请选择检测时间", trigger: "change" }],
  inspectionUnit: [{ required: true, message: "请输入检测单位", trigger: "blur" }],
  inspectionMethod: [{ required: true, message: "请输入检测方法", trigger: "blur" }],
  healthScore: [{ required: true, message: "请输入健康评分", trigger: "blur" }],
  mainIssues: [{ required: true, message: "请输入发现的问题", trigger: "blur" }],
  measure: [{ required: true, message: "请输入维护措施", trigger: "blur" }],
  reportFilePath: [{ required: true, message: "请输入报告文件路径", trigger: "blur" }],
};

// 获取健康评分对应的标签类型
const getHealthScoreType = (score: number) => {
  if (score >= 80) return "success";
  if (score >= 60) return "warning";
  return "danger";
};

// 获取列表数据
const getList = async () => {
  loading.value = true;
  try {
    const params: any = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchQuery.value,
    };
    
    // 如果有桥梁ID参数，添加到查询条件
    if (bridgeIdFromRoute.value) {
      params.bridgeId = bridgeIdFromRoute.value;
    }
    
    const res = await getBridgeHealthReportList(params);
    // 格式化返回数据中的时间
    tableData.value = res.rows.map(item => ({
      ...item,
      inspectionTime: item.inspectionTime ? dayjs(item.inspectionTime).format('YYYY-MM-DD HH:mm:ss') : ''
    }));
    total.value = res.total;
  } catch (error) {
    console.error("获取数据失败:", error);
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  getList();
};

// 处理新增
const handleAdd = () => {
  dialogTitle.value = "新增数据";
  form.value = {
    id: "",
    bridgeId: bridgeIdFromRoute.value || "",
    bridgeName: "",
    inspectionTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
    inspectionUnit: "",
    inspectionMethod: "",
    healthScore: 0,
    mainIssues: "",
    measure: "",
    reportFilePath: "",
    remarks: "",
  };
  dialogVisible.value = true;
};

// 处理编辑
const handleEdit = async (row: any) => {
  try {
    const res = await getBridgeHealthReportById(row.id);
    form.value = {
      ...res.data,
      inspectionTime: res.data.inspectionTime ? dayjs(res.data.inspectionTime).format('YYYY-MM-DD HH:mm:ss') : dayjs().format('YYYY-MM-DD HH:mm:ss')
    };
    dialogTitle.value = "编辑数据";
    dialogVisible.value = true;
  } catch (error) {
    ElMessage.error("获取详情失败");
  }
};

// 处理查看
const handleView = async (row: any) => {
  try {
    const res = await getBridgeHealthReportById(row.id);
    form.value = {
      ...res.data,
      inspectionTime: res.data.inspectionTime ? dayjs(res.data.inspectionTime).format('YYYY-MM-DD HH:mm:ss') : dayjs().format('YYYY-MM-DD HH:mm:ss')
    };
    dialogTitle.value = "查看详情";
    dialogVisible.value = true;
  } catch (error) {
    ElMessage.error("获取详情失败");
  }
};

// 处理删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm("确认删除该条数据吗？", "提示", {
    type: "warning",
  }).then(async () => {
    try {
      await deleteBridgeHealthReport(row.id);
      ElMessage.success("删除成功");
      getList();
    } catch (error) {
      ElMessage.error("删除失败");
    }
  });
};

// 处理批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要删除的数据");
    return;
  }
  ElMessageBox.confirm("确认删除选中的数据吗？", "提示", {
    type: "warning",
  }).then(async () => {
    try {
      await Promise.all(
        selectedRows.value.map((row) => deleteBridgeHealthReport(row.id))
      );
      ElMessage.success("批量删除成功");
      getList();
    } catch (error) {
      ElMessage.error("批量删除失败");
    }
  });
};

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const submitData = {
          ...form.value,
          inspectionTime: dayjs(form.value.inspectionTime).format('YYYY-MM-DD HH:mm:ss')
        };
        
        if (form.value.id) {
          await updateBridgeHealthReport(submitData);
          ElMessage.success("修改成功");
        } else {
          await addBridgeHealthReport(submitData);
          ElMessage.success("新增成功");
        }
        dialogVisible.value = false;
        getList();
      } catch (error) {
        ElMessage.error("操作失败");
      }
    }
  });
};

// 显示备注信息
const showRemarks = (row: any) => {
  currentRemarks.value = row.remarks || "暂无备注";
  remarksDialogVisible.value = true;
};

// 表格选择改变
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows;
};

// 分页相关方法
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  getList();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  getList();
};

// 显示问题信息
const showIssues = (row: any) => {
  currentIssues.value = row.mainIssues || "暂无问题记录";
  issuesDialogVisible.value = true;
};

// 显示措施信息
const showMeasures = (row: any) => {
  currentMeasures.value = row.measure || "暂无维护措施";
  measuresDialogVisible.value = true;
};

// 显示报告文件路径
const showReport = (row: any) => {
  currentReport.value = row.reportFilePath || "暂无文件路径";
  reportDialogVisible.value = true;
};
const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 100000000,
  dictType: '',
})
// 获取桥梁列表数据
const getBridgeOptions = async () => {
  try {
    const res = await getBridgeList(queryParams.value);
    bridgeOptions.value = res.rows.map((item) => ({
      value: item.id,
      label: item.bridgeName,
    }));
  } catch (error) {
    console.error("获取桥梁列表失败:", error);
    ElMessage.error("获取桥梁列表失败");
  }
};

onMounted(() => {
  // 初始化时获取路由参数
  if (route.query.bridgeId) {
    bridgeIdFromRoute.value = route.query.bridgeId as string;
  }
  
  getList();
  getBridgeOptions();
});
watch(
  () => route.query.bridgeId,
  (newVal) => {
    if (newVal) {
      bridgeIdFromRoute.value = newVal as string;
    } else {
      bridgeIdFromRoute.value = null;
    }
    getList();
  },
  { immediate: true }
);
</script>

<style scoped lang="scss">
.page-container {
  display: flex;
  height: 100%;
  background: var(--el-bg-color-page);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
  overflow: hidden;
}

.bridge-health-container {
  flex: 1;
  padding: 20px;
  overflow: auto;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  background: var(--el-bg-color-overlay);
  padding: 16px;
  border-radius: 4px;

  .left {
    .page-selector {
      width: 180px;
      
      :deep(.el-input__wrapper) {
        background-color: transparent;
        box-shadow: none !important;
        
        &:hover {
          background-color: var(--el-fill-color-light);
        }
      }

      :deep(.el-input__inner) {
        font-size: 16px;
        font-weight: 500;
        color: var(--el-color-primary);
      }

      :deep(.el-select-dropdown__item) {
        &.is-active {
          color: var(--el-color-primary);
          font-weight: bold;
          background-color: var(--el-color-primary-light-9);
        }

        &:hover {
          background-color: var(--el-color-primary-light-9);
        }
      }
    }
  }

  .custom-button {
    margin-left: 10px;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-2px);
    }
  }
}

.custom-table {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  background: var(--el-bg-color-overlay);

  :deep(th) {
    background: var(--el-bg-color-page) !important;
  }

  :deep(.el-table__row) {
    background-color: var(--el-bg-color-overlay);
  }

  .bridge-name {
    color: var(--el-color-primary);
    cursor: pointer;

    &:hover {
      text-decoration: underline;
    }
  }

  .operation-button {
    padding: 0 10px;
    font-size: 14px;

    &.danger {
      color: var(--el-color-danger);
    }

    &:hover {
      opacity: 0.8;
    }
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.custom-dialog {
  :deep(.el-dialog) {
    border-radius: 12px;
    background: var(--el-bg-color-overlay);

    .el-dialog__header {
      background: var(--el-bg-color-page);
      margin: 0;
      padding: 20px;
      border-bottom: 1px solid var(--el-border-color-light);
    }

    .el-dialog__body {
      padding: 30px 20px;
    }

    .el-dialog__footer {
      border-top: 1px solid var(--el-border-color-light);
      padding: 15px 20px;
    }
  }

  .dialog-form {
    :deep(.el-form-item__label) {
      color: var(--el-text-color-regular);
    }

    :deep(.el-input__inner) {
      background-color: var(--el-bg-color-overlay);
      border-color: var(--el-border-color);
      color: var(--el-text-color-primary);
    }
  }
}

// 自定义 Element Plus 组件样式
:deep(.el-table) {
  --el-table-border-color: var(--el-border-color-light);
  --el-table-header-bg-color: var(--el-bg-color-page);
  --el-table-row-hover-bg-color: var(--el-fill-color-light);
}

:deep(.el-button--primary) {
  //   background: var(--el-color-primary);
  //   border-color: var(--el-color-primary);

  &:hover {
    background: var(--el-color-primary-light-3);
    border-color: var(--el-color-primary-light-3);
  }
}

:deep(.el-tag) {
  border-radius: 4px;
  padding: 0 10px;
  background-color: var(--el-fill-color);
  border-color: var(--el-border-color-light);
  color: var(--el-text-color-regular);
}

.ellipsis {
  display: inline-block;
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.ellipsis-text {
  cursor: pointer;
  color: var(--el-color-primary);
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;

  &:hover {
    text-decoration: underline;
    opacity: 0.8;
  }
}
</style>
